import { callCloudFun } from "../utiles/callCloudFun"

const db = wx.cloud.database()
const _ = db.command

export const getAdminOrderDetailListByStatusApi = async (params : any) => {
	let { job, keyword } = params
	let conditions = []
	try {
		wx.showLoading({ title: '稍候...', mask: true })
		let orderDetails = []
		if (keyword) {
			if (keyword.length <= 3 && !isNaN(keyword)) {
				conditions.push(_.or([{ name: db.RegExp({ regexp: keyword }) }, { place: _.eq(Number(keyword)) }]));
			} else {
				conditions.push({ name: db.RegExp({ regexp: keyword }) })
			}
		}
		conditions.push({ place: _.lt(500) })
		if (job === '服务员') {
			({ data: orderDetails } = await db.collection('order_detail').where(_.and([{ status: _.eq(2) }, ...conditions])).limit(20).orderBy('completeTime', 'asc').get())
		} else if (job === '厨师') {
			const userInfo = wx.getStorageSync('userInfo')
			const { data: orderDetails1 } = await db.collection('order_detail').where(_.and([{ status: _.eq(1), chefId: _.eq(userInfo.name) }, ...conditions])).limit(20).orderBy('completeTime', 'asc').get()
			const { data: orderDetails0 } = await db.collection('order_detail').where(_.and([{ status: _.eq(0) }, ...conditions])).limit(20).orderBy('completeTime', 'asc').get()
			orderDetails = [...orderDetails1, ...orderDetails0]
		} else if (job === '管理员' || job === '收银员') {
			const { data: orderDetails0 } = await db.collection('order_detail').where(_.and([{ status: _.eq(0) }, ...conditions])).limit(20).orderBy('completeTime', 'asc').get()
			const { data: orderDetails1 } = await db.collection('order_detail').where(_.and([{ status: _.eq(1) }, ...conditions])).limit(20).orderBy('completeTime', 'asc').get()
			const { data: orderDetails2 } = await db.collection('order_detail').where(_.and([{ status: _.eq(2) }, ...conditions])).limit(20).orderBy('completeTime', 'asc').get()
			orderDetails = [...orderDetails0, ...orderDetails1, ...orderDetails2]
		}
		await wx.hideLoading()
		return orderDetails
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error?.message || "获取数据失败", icon: 'none' })
		throw error
	}
}

export const putAdminOrderDetailUpdateApi = async (params : any, isShow : boolean = true) => {
	let step = 0
	let data = null
	try {
		if (isShow) {
			wx.showLoading({ title: '稍等...', mask: true });
		}
		({ data } = await db.collection('order_detail').doc(params.id).get())
		step = 1
		if (params.orderId) {
			if (data.status === params.status || params.orderId !== data.orderId || data.status === 4) {
				throw new Error('状态错误，刷新重试')
			}
			delete params.orderId
		} else {
			if (params.status !== 4 && data.status !== params.status - 1) {
				throw new Error('状态错误，刷新重试')
			}
		}
		delete params.id
		params.completeTime = db.serverDate()
		await db.collection('order_detail').doc(data._id).update({ data: params })
		step = 2
		if (params.status === 1 || params.status === 2) {
			if (isShow) await wx.hideLoading()
			return
		}
		let updateData = {} as any
		let allorderDetailList = []
		for (let i = 0; ; i += 20) {
			const res = await db.collection('order_detail').where(_.and({ orderId: _.eq(data.orderId), status: _.lt(4) })).skip(i).limit(20).get()
			if (res.data.length === 0) break
			allorderDetailList.push(...res.data)
			if (res.data.length < 20) break
		}
		if (!allorderDetailList || allorderDetailList.length === 0) {
			updateData = {
				status: 4,
				amount: 0,
				cancelTime: db.serverDate(),
				cancelReason: '用户取消'
			}
		} else {
			const undoneList = allorderDetailList.filter(item => item.status !== 3)
			if (params.status === 3 && undoneList.length !== 0) {
				if (isShow) await wx.hideLoading()
				return
			}
			updateData.amount = allorderDetailList.reduce((acc, cur) => acc + cur.amount * cur.number, 0)
			if (undoneList.length === 0) {
				updateData.status = 3
				updateData.completeTime = db.serverDate()
			}
		}
		await db.collection('orders').doc(data.orderId).update({ data: updateData })
		if (isShow) await wx.hideLoading()
		return
	} catch (e) {
		if (isShow) await wx.hideLoading()
		//模拟事务管理
		if (step === 2) {
			const { _id, ...rollbackData } = data
			db.collection('order_detail').doc(_id).update({ data: rollbackData })
		}
		wx.showToast({ title: e.message || (e as any).errMsg || '操作失败，请刷新重新', icon: 'none' })
		throw e
	}
}

export const getAdminTurnoverDoingListApi = async () => {
	let turnoverDoingList = []
	for (var i = 0; ; i += 20) {
		const { data } = await db.collection('turnover').where({ status: _.lt(2) }).orderBy('place', 'asc').skip(i).limit(20).get()
		if (data.length === 0) break
		turnoverDoingList.push(...data)
		if (data.length < 20) break
	}
	return turnoverDoingList
}

// 清台
export const putAdminTurnoverUpdateApi = async (params : any) => {
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		const { data: turnover } = await db.collection('turnover').doc(params.id).get()
		if (turnover.status === 2) {
			throw new Error(turnover.place + '号桌未使用，或已清台')
		}
		if (turnover.place !== params.place) {
			throw new Error(params.place + '号桌换到' + turnover.place + '号桌了，请刷新重试')
		}
		const { data: unPayOrders } = await db.collection('orders').where(_.and([{ turnoverId: turnover._id }, { status: _.lt(4) }, { statementId: _.eq(null) }])).get()
		if (unPayOrders && unPayOrders.length !== 0) {
			throw new Error('有未结账单，不能清台')
		}
		try {
			await callCloudFun('batchDel', { name: 'shopping_cart', where: { turnoverId: params.id } })
		} catch (error) {
			console.log('批量删除失败');
		}
		await db.collection('turnover').doc(params.id).update({ data: { status: 2 } })
		wx.hideLoading()
		return
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error?.message || '清台失败', icon: 'none' })
		throw error
	}
}

export const putAdminTurnoverChangePlaceApi = async (params : any) => {
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		const { data: turnoverDoings } = await db.collection('turnover').where({ status: _.lt(2) }).get()
		let currentTurnover = null
		for (let turnover of turnoverDoings) {
			if (turnover.place === params.toPlace) {
				throw new Error(params.toPlace + "号桌正在被使用，等结账后再试")
			}
			if (turnover.place === params.fromPlace) {
				if (params.turnoverId && params.turnoverId !== turnover._id) {
					throw new Error(params.fromPlace + "号桌有异常，刷新重试")
				}
				currentTurnover = turnover
			}
		}
		if (!currentTurnover) {
			throw new Error(params.fromPlace + '号桌异常，请确认该桌正在被使用')
		}
		await db.collection('turnover').doc(currentTurnover._id).update({ data: { place: params.toPlace } })
		const { data: undoneList } = await db.collection('order_detail').where(_.and([{ status: _.lt(3) }, { place: _.eq(params.fromPlace) }])).get()
		await Promise.all(undoneList.map(item => db.collection('order_detail').doc(item._id).update({ data: { place: params.toPlace } })))
		wx.hideLoading()
		return
	} catch (error) {
		wx.hideLoading()
		wx.showToast({ title: error?.message || '换桌失败，请重试', icon: 'none' })
		throw error
	}
}

export const getAutoAcceptOrder = async () => {
	const { data: [{ sex: autoAccept = '1' }] } = await db.collection('employee').field({ sex: true, _id: false }).where({ username: 'admin' }).get()
	return autoAccept
}